﻿using Lightworks.Core.Repository;
using Lightworks.Core.Service;
using Lightworks.System.Dto;
using Lightworks.System.Models;
using Microsoft.Extensions.Logging;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Lightworks.System.Services.Impl
{
    [Service]
    public class DictService : IDictService
    {
        SugarRepository<SysDict> _sysDictRepository;
        SugarRepository<SysDictDetail> _sysDictDetailRepository;
        ILogger<DictService> _logger;

        public DictService(SugarRepository<SysDict> dictRepo,
            SugarRepository<SysDictDetail> dictDetailRepo,
            ILogger<DictService> logger) 
        { 
            _sysDictRepository = dictRepo;
            _sysDictDetailRepository = dictDetailRepo;
            _logger = logger;
        }
        

        public bool ChangeStatus(long id, bool status)
        {
            return _sysDictDetailRepository
                .UpdateSetColumnsTrue(d=> new SysDictDetail { Status = status },d=>d.Id==id);
        }

        public bool DeleteDetails(dynamic[] ids)
        {
            return _sysDictDetailRepository.DeleteByIds(ids);
        }

        public bool DeleteDict(long id)
        {
            return _sysDictRepository.DeleteById(id);
        }

        public List<SysDict> GetAll()
        {
            return _sysDictRepository.GetList();
        }

        public PageData<SysDictDetail> GetDetail(DictSearchReq req)
        {
            PageData<SysDictDetail> result = new PageData<SysDictDetail>();
            var pageModel = new PageModel { PageSize = req.PageSize, PageIndex = req.Page };
            result.Rows =  _sysDictDetailRepository.GetPageList(
                d => d.Code == req.Code, pageModel);
            result.Total = pageModel.TotalCount;
            return result;
        }

        public bool SaveDetail(SysDictDetail model)
        {
            try
            {
                return _sysDictDetailRepository.InsertOrUpdate(model);
            }
            catch (Exception e) {
                _logger.LogError(e,e.Message); 
                return false;    
            }

        }

        public bool SaveDict(SysDict model)
        {
            try
            {
                return _sysDictRepository.InsertOrUpdate(model);
            }
            catch (Exception ex) 
            {
                _logger.LogError(ex, ex.Message);
                return false;
            }
        }
    }
}
